<template>
  <div class="lending-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>放款列表</h3>
          <el-button type="primary" @click="exportData">导出数据</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="放款状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待放款" value="pending" />
            <el-option label="已放款" value="completed" />
            <el-option label="放款失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="放款日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 放款列表 -->
      <el-table :data="lendingList" style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="loanAmount" label="贷款金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="approvedAmount" label="放款金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.approvedAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanTerm" label="贷款期限" width="120">
          <template #default="scope">
            {{ scope.row.loanTerm }}个月
          </template>
        </el-table-column>
        <el-table-column prop="lendingDate" label="放款日期" width="180" />
        <el-table-column prop="status" label="放款状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bankAccount" label="收款账号" width="200" />
        <el-table-column prop="bankName" label="开户行" width="180" />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleLending(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              放款
            </el-button>
            <el-button
              link
              type="primary"
              @click="viewDetail(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 放款对话框 -->
    <el-dialog
      v-model="lendingDialogVisible"
      title="执行放款"
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="lendingFormRef"
        :model="lendingForm"
        :rules="lendingRules"
        label-width="120px"
      >
        <el-descriptions title="放款信息" :column="2" border>
          <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
          <el-descriptions-item label="放款金额">{{ formatAmount(currentLoan.approvedAmount) }}</el-descriptions-item>
          <el-descriptions-item label="放款日期">{{ currentLoan.lendingDate }}</el-descriptions-item>
        </el-descriptions>

        <el-form-item label="收款账号" prop="bankAccount">
          <el-input v-model="lendingForm.bankAccount" placeholder="请输入收款账号" />
        </el-form-item>

        <el-form-item label="开户行" prop="bankName">
          <el-input v-model="lendingForm.bankName" placeholder="请输入开户行" />
        </el-form-item>

        <el-form-item label="支付渠道" prop="payChannel">
          <el-select v-model="lendingForm.payChannel" placeholder="请选择支付渠道">
            <el-option label="网银支付" value="online" />
            <el-option label="快速支付" value="fast" />
            <el-option label="银企直连" value="direct" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="lendingForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="lendingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLending(lendingFormRef)">
            确认放款
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="放款详情"
      width="70%"
    >
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatAmount(currentLoan.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="放款金额">{{ formatAmount(currentLoan.approvedAmount) }}</el-descriptions-item>
        <el-descriptions-item label="放款状态">
          <el-tag :type="getStatusType(currentLoan.status)">
            {{ getStatusText(currentLoan.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="放款日期">{{ currentLoan.lendingDate }}</el-descriptions-item>
        <el-descriptions-item label="收款账号">{{ currentLoan.bankAccount }}</el-descriptions-item>
        <el-descriptions-item label="开户行">{{ currentLoan.bankName }}</el-descriptions-item>
      </el-descriptions>

      <!-- 放款流水 -->
      <el-table
        :data="lendingRecords"
        style="width: 100%; margin-top: 20px"
        border
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="transactionNo" label="交易流水号" width="200" />
        <el-table-column prop="amount" label="交易金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="payChannel" label="支付渠道" width="120" />
        <el-table-column prop="status" label="交易状态" width="100">
          <template #default="scope">
            <el-tag :type="getTransactionStatusType(scope.row.status)">
              {{ getTransactionStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="交易时间" width="180" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { lendingApi } from '@/api/lending'

export default {
  name: 'LendingList',
  setup() {
    // 状态管理
    const loading = ref(false)
    const lendingList = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const lendingDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentLoan = ref({})
    const lendingRecords = ref([])
    const lendingFormRef = ref(null)

    // 搜索表单
    const searchForm = reactive({
      contractNo: '',
      loanNo: '',
      customerName: '',
      status: '',
      dateRange: []
    })

    // 放款表单
    const lendingForm = reactive({
      bankAccount: '',
      bankName: '',
      payChannel: '',
      remark: ''
    })

    // 表单验证规则
    const lendingRules = {
      bankAccount: [
        { required: true, message: '请输入收款账号', trigger: 'blur' }
      ],
      bankName: [
        { required: true, message: '请输入开户行', trigger: 'blur' }
      ],
      payChannel: [
        { required: true, message: '请选择支付渠道', trigger: 'change' }
      ]
    }

    // 获取放款列表
    const getLendingList = async () => {
      try {
        loading.value = true
        // 准备请求参数
        const params = {
          contractNo: searchForm.contractNo,
          loanNo: searchForm.loanNo,
          customerName: searchForm.customerName,
          status: searchForm.status,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 处理日期范围
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.startDate = searchForm.dateRange[0]
          params.endDate = searchForm.dateRange[1]
        }
        
        const res = await lendingApi.getList(params)
        lendingList.value = res.data.list
        total.value = res.data.total
      } catch (error) {
        console.error('获取放款列表失败', error)
        ElMessage.error('获取放款列表失败')
      } finally {
        loading.value = false
      }
    }

    // 导出数据
    const exportData = async () => {
      try {
        loading.value = true
        // 准备请求参数，与搜索条件一致
        const params = {
          contractNo: searchForm.contractNo,
          loanNo: searchForm.loanNo,
          customerName: searchForm.customerName,
          status: searchForm.status
        }
        
        // 处理日期范围
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.startDate = searchForm.dateRange[0]
          params.endDate = searchForm.dateRange[1]
        }
        
        const res = await lendingApi.exportList(params)
        
        // 处理文件下载
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const fileName = `放款记录_${new Date().toISOString().split('T')[0]}.xlsx`
        
        if (window.navigator.msSaveOrOpenBlob) {
          // IE浏览器支持
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          // 其他浏览器
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          URL.revokeObjectURL(link.href)
        }
        
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败', error)
        ElMessage.error('导出失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }

    // 查看详情
    const viewDetail = async (row) => {
      try {
        loading.value = true
        const res = await lendingApi.getDetail(row.disbursementId)
        currentLoan.value = res.data
        detailDialogVisible.value = true
        
        // 这里可以根据后端接口增加获取放款记录流水的调用
        // 为简化示例，暂未实现
      } catch (error) {
        console.error('获取详情失败', error)
        ElMessage.error('获取详情失败')
      } finally {
        loading.value = false
      }
    }

    // 处理放款
    const handleLending = (row) => {
      currentLoan.value = row
      // 预填表单信息
      lendingForm.bankAccount = row.bankAccount || ''
      lendingForm.bankName = row.bankName || ''
      lendingForm.payChannel = ''
      lendingForm.remark = ''
      lendingDialogVisible.value = true
    }

    // 提交放款
    const submitLending = async (formEl) => {
      if (!formEl) return
      
      await formEl.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            
            // 准备放款处理数据
            const processData = {
              disbursementId: currentLoan.value.disbursementId,
              disburseTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
              transactionNo: 'TX' + new Date().getTime(), // 这里应该由后端生成
              status: '30', // 放款成功
              bankAccount: lendingForm.bankAccount,
              bankName: lendingForm.bankName,
              remark: lendingForm.remark
            }
            
            await lendingApi.process(processData)
            
            ElMessage.success('放款操作成功')
            lendingDialogVisible.value = false
            getLendingList() // 刷新列表
          } catch (error) {
            console.error('放款失败', error)
            ElMessage.error('放款操作失败')
          } finally {
            loading.value = false
          }
        }
      })
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getLendingList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      searchForm.dateRange = []
      currentPage.value = 1
      getLendingList()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      getLendingList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      getLendingList()
    }

    // 对话框关闭处理
    const handleDialogClose = () => {
      lendingDialogVisible.value = false
    }

    // 格式化金额
    const formatAmount = (amount) => {
      if (!amount && amount !== 0) return '--'
      return Number(amount).toLocaleString('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
      })
    }

    // 获取状态类型和文本
    const getStatusType = (status) => {
      const statusMap = {
        '10': 'warning', // 待审批
        '20': 'primary', // 处理中
        '30': 'success', // 放款成功
        '40': 'danger' // 放款失败
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        '10': '待审批',
        '20': '处理中',
        '30': '放款成功',
        '40': '放款失败'
      }
      return statusMap[status] || '未知状态'
    }

    // 交易状态类型和文本
    const getTransactionStatusType = (status) => {
      const statusMap = {
        'success': 'success',
        'pending': 'warning',
        'failed': 'danger'
      }
      return statusMap[status] || 'info'
    }

    const getTransactionStatusText = (status) => {
      const statusMap = {
        'success': '交易成功',
        'pending': '处理中',
        'failed': '交易失败'
      }
      return statusMap[status] || '未知状态'
    }

    onMounted(() => {
      getLendingList()
    })

    return {
      loading,
      lendingList,
      total,
      currentPage,
      pageSize,
      searchForm,
      lendingDialogVisible,
      detailDialogVisible,
      currentLoan,
      lendingRecords,
      lendingForm,
      lendingRules,
      lendingFormRef,
      getLendingList,
      exportData,
      handleLending,
      viewDetail,
      submitLending,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleDialogClose,
      formatAmount,
      getStatusType,
      getStatusText,
      getTransactionStatusType,
      getTransactionStatusText
    }
  }
}
</script>

<style scoped>
.lending-list {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}
</style> 